#!/usr/bin/python
# -*- encoding: utf-8

import urllib, urllib2, re, xbmcplugin, xbmcgui
import webutils
import CommonFunctions
import xbmcaddon
import time #remove

common = CommonFunctions
common.plugin = "HusteTv-1.0"

def index():
    print "showIndex"
    
    text = webutils.tryGetTextFromUrl("http://zabava.huste.tv")
    
    if text is None:
        addErrorText("Unable to load content. Click to retry.")
    else:                
        print "got response"
        
        elements = common.parseDOM(text, "select", attrs={ "class" : "j-selectmenu" })
        urls = common.parseDOM(elements, "option", ret="value")
        names = common.parseDOM(elements, "option")
        
        print "parsed"    
        
        for url, name in zip(urls, names):
            u = sys.argv[0] + "?sub=" + url
            addFolder(name, u)
            
        print "index done (items added)"
            
    print "index done (items added)"
        
def addFolder(name, u):
    print "addFolder " + u
    print "handle " + sys.argv[1]
    liz = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage="DefaultItem.png")
    liz.setInfo(type="Video", infoLabels={ "Title": name })
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True )

def subIndex(subUrl, pageNo):
    print "subIndex " + subUrl + " " + str(pageNo)
    
    text = webutils.tryGetTextFromUrl("http://zabava.huste.tv" + subUrl)
    
    if text is None:
        addErrorText("Unable to load content. Click to retry.")
    else:                
        print "got response"
    
        videoids = common.parseDOM(text, "a", attrs={ "class" : "x-button" }, ret="data-targetclip")
        videonames = common.parseDOM(text, "a", attrs={ "class" : "x-button" }, ret="title")
        
        print "parsed"    
        
        for id, name in zip(videoids, videonames):
            u = sys.argv[0] + "?&videoID=" + id
            addLink(name, u, "DefaultFolder.png")
            
        print "index done (items added)"

def addErrorText(error):
    print "error " + error
    print sys.exc_info()[0]
    liz = xbmcgui.ListItem(error, iconImage="DefaultFolder.png", thumbnailImage="DefaultFolder.png")
    liz.setInfo(type="Video", infoLabels={ "Title": error })
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sys.argv[0], listitem=liz)

def playVideoID(id):
    print "playVideo", id
    dialog = xbmcgui.DialogProgress()
    dialog.create('Husté TV', 'Otváram video...')
    
    url = 'http://www.huste.tv/services/Video.php?clip=' + str(id)
    
    print "requesting url", url
    
    text = webutils.tryGetTextFromUrl(url)
    
    if text is None:
        dialog.close()
        addError("Unable to load video.")
    else:
        print "got response"
        
        videoUrl = 'http://' + re.search('quality="hi".*rtmp://([a-z0-9]+)', text).group(1) + '.joj.sk/' + re.search('"540p" path="(.*?)"', text).group(1) #TODO: hardcoded
        print "parsed video url", videoUrl
    
        dialog.close()
        xbmc.Player().play(videoUrl)
        
        print "playVideo done (sent to xbmc)"

def get_params():
    param = []
    paramstring = sys.argv[2]
    if len(paramstring) >= 2:
        params = sys.argv[2]
        cleanedparams = params.replace('?', '')
        if (params[len(params) - 1] == '/'):
            params = params[0:len(params) - 2]
        pairsofparams = cleanedparams.split('&')
        param = {}
        for i in range(len(pairsofparams)):
            splitparams = {}
            splitparams = pairsofparams[i].split('=')
            if (len(splitparams)) == 2:
                param[splitparams[0]] = splitparams[1]
                            
    return param

def addLink(name, url, iconimage):
    liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
    liz.setInfo(type="Video", infoLabels={ "Title": name })
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=liz)


print "hustetv plugin"
params = get_params()

subUrl = None
videoID = None
 
try: 
  videoID = params["videoID"]
except:
  pass

try: 
  subUrl = params["sub"]
except:
  pass
  
print "video " + str(videoID)
print "sub " + str(subUrl)

if videoID is not None:
    playVideoID(videoID)
elif subUrl is not None:
    subUrl = urllib2.unquote(subUrl)
    subIndex(subUrl, 0)    
else:
    index()  

xbmcplugin.endOfDirectory(int(sys.argv[1]))
